﻿using ControleRepresentante.Logic.Models;
using NHibernate;
using NHibernate.Criterion;

namespace ControleRepresentante.Logic.Repositories.SearchExtensions
{
    public class ClienteJolitexSearchExtension : ISearchExtension
    {
        private readonly int? m_Codigo;
        private readonly int? m_Regiao;

        public ClienteJolitexSearchExtension(int? codigo, int? regiao)
        {
            m_Codigo = codigo;
            m_Regiao = regiao;
        }

        public ICriteria Execute(ICriteria criteria, string tableAlias)
        {
            if (m_Codigo.HasValue || m_Regiao.HasValue)
            {
                DetachedCriteria detachedCriteria = DetachedCriteria.For<ClienteJolitex>()
                    .SetProjection(Projections.Property<ClienteJolitex>(x => x.Id))
                    .Add(Restrictions.EqProperty(tableAlias + ".Id", Projections.Property<ClienteJolitex>(x => x.Id)));

                if (m_Codigo.HasValue)
                {
                    detachedCriteria.Add(Restrictions.Eq(Projections.Property<ClienteJolitex>(x => x.Codigo), m_Codigo.Value));
                }

                if (m_Regiao.HasValue)
                {
                    detachedCriteria.Add(Restrictions.Eq(Projections.Property<ClienteJolitex>(x => x.Regiao), m_Regiao.Value));
                }

                criteria = criteria.Add(Subqueries.Exists(detachedCriteria));
            }
            return criteria;
        }
    }
}
